package com.plate.auth.config;

import com.plate.api.system.domain.SysUser;
import com.plate.auth.domain.LoginUser;
import com.plate.common.core.constants.TokenConstant;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.Map;

/**
 * @ClassName JwtEnhanceUserAuthenticationConverter
 * @Description 从map中提提取用户信息
 * @Author jiaxd
 * @Date 2023年10月29日 22:59
 * @Version 1.0
 */

public class JwtEnhanceUserAuthenticationConverter extends DefaultUserAuthenticationConverter {

    /**
     * 重写抽取用户数据方法
     */
    @Override
    public Authentication extractAuthentication(Map<String, ?> map) {
        if (map.containsKey(USERNAME)) {
            Collection<? extends GrantedAuthority> authorities = getAuthorities(map);
            String username = (String) map.get(USERNAME);
            Long userId = Long.parseLong(map.get(TokenConstant.USER_ID).toString());
            SysUser sysUser = new SysUser();
            sysUser.setUsername(username);
            sysUser.setId(userId);
            LoginUser user =new LoginUser(sysUser);
            return new UsernamePasswordAuthenticationToken(user, "", null);
        }
        return null;
    }

    /**
     * 提取权限
     */
    protected Collection<? extends GrantedAuthority> getAuthorities(Map<String, ?> map) {
        Object authorities = map.get(AUTHORITIES);
        if (authorities instanceof String) {
            return AuthorityUtils.commaSeparatedStringToAuthorityList((String) authorities);
        }
        if (authorities instanceof Collection) {
            return AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils
                    .collectionToCommaDelimitedString((Collection<?>) authorities));
        }
        throw new IllegalArgumentException("Authorities must be either a String or a Collection");
    }

}
